package controller;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static java.lang.System.out;

@Controller
public class UserController {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    public UserController() throws IOException {
    }

    //跳转到登录页面
    @RequestMapping("/tologin")
    public String toLoginPage() {
        return "login.jsp";
    }

    //跳转到管理员首页
    @RequestMapping("/management_index")
    public String toManagerPage() {
        return "management_index.jsp";
    }

    //跳转到教师首页
    @RequestMapping("/teacher_index")
    public String toTeacherPage() {
        return "teacher_index.jsp";
    }

    //跳转到学生首页
    @RequestMapping("/student_index")
    public String toStudentPage() {
        return "student_index.jsp";
    }

    //跳转到管理员个人信息页面
    @RequestMapping("/managerInfo")
    public String managerInfo() {
        return "managerInfo.jsp";
    }

    //跳转到教师个人信息页面
    @RequestMapping("/teacherInfo")
    public String teacherInfo() {
        return "teacherInfo.jsp";
    }

    //跳转到学生个人信息页面
    @RequestMapping("/studentInfo")
    public String studentInfo() {
        return "studentInfo.jsp";
    }

    //跳转到教师信息页面
    @RequestMapping("/teacherList")
    public String teacherList() {
        return "teacherList.jsp";
    }

    //跳转到学生信息页面
    @RequestMapping("/studentList")
    public String studentList() {
        return "studentList.jsp";
    }

    //跳转到管理员添加教师页面
    @RequestMapping("/teacher_add")
    public String teacher_add() {
        return "teacher_add.jsp";
    }

    //跳转到管理员添加学生页面
    @RequestMapping("/student_add")
    public String student_add() {
        return "student_add.jsp";
    }

    //跳转到教师端学生页面
    @RequestMapping("/teacher_studentList")
    public String teacher_studentList() {
        return "teacher_studentList.jsp";
    }

    /**
     * 用户注册
     */
    @RequestMapping("/register")
    public String register(Student student, Model model, HttpSession session) {
        Student student1 = new Student();
        int studentId = student.getS_id();
        String studentName = student.getS_name();
        String studentCollege = student.getCollege();
        String studentClass = student.getS_class();
        String studentPhone = student.getS_phone();
        String studentPassword = student.getS_pwd();
        student1.setS_id(studentId);
        student1.setS_name(studentName);
        student1.setCollege(studentCollege);
        student1.setS_class(studentClass);
        student1.setS_phone(studentPhone);
        student1.setS_pwd(studentPassword);
        out.println(studentId + studentName + studentCollege + studentClass + studentPhone + studentPassword);
        //判断用户是否已存在
        if (studentId != 0 && (!studentName.equals("")) && (!studentCollege.equals("")) && (!studentClass.equals("")) && (!studentPhone.equals("")) && (!studentPassword.equals(""))) {
            Student u = sqlSession.selectOne("mapper.Student.findStudentByStudentId", studentId);
            if (u != null) {
                //如果用户名已存在，转发到注册页面并继续提醒
                model.addAttribute("wrongMsg", "该用户已存在！");
                out.println("该用户已存在");
                return "register.jsp";
            } else {
                //用户还没有注册则注册新账号
                int rows = sqlSession.insert("mapper.Student.addStudent", student1);
                if (rows > 0) {
                    out.print("您成功插入了" + rows + "个用户！\n");
                    session.setAttribute("zhucetanchuang","true");
                } else {
                    out.print("执行插入操作失败！\n");
                }
                sqlSession.commit();
                return "redirect:tologin";
            }
        }
        return "register.jsp";
    }

    /**
     * 登录
     */
    @RequestMapping("/login")
    public String login(@RequestParam int username, @RequestParam String password, @RequestParam String sysType, Model model, HttpSession session) {
        if (sysType.equals("student")) {
            //获取学号和密码
            int StudentId = username;
            String StudentPwd = password;
            //从数据库Student表中获取学号和密码后进行判断
            if (StudentId != 0 && StudentPwd != null) {
                Student s = sqlSession.selectOne("mapper.Student.findStudentByStudentIds", StudentId);
                if (s == null) {
                    //如果学号不在数据库，转发到登录页面并进行提醒
                    model.addAttribute("msg", "用户名错误，请重新登录！");
                    out.println("用户名错误，请重新登录");
                    return "login.jsp";
                } else if (!s.getS_pwd().equals(StudentPwd)) {
                    //如果密码不匹配，转发到登录页面并进行提醒
                    model.addAttribute("msg", "密码错误，请重新登录！");
                    out.println("密码错误，请重新登录");
                    return "login.jsp";
                } else if ((s.getS_id() == StudentId) && (s.getS_pwd().equals(StudentPwd))) {
                    session.setAttribute("STUDENT_SESSION", StudentId);
                    Student s1 = sqlSession.selectOne("mapper.Student.findStudentByStudentIds", StudentId);
                    out.println(s1.getS_name());
                    session.setAttribute("LOGIN_STUDENT", s1);
                    session.setAttribute("STUDENT_NAME", s1.getS_name());
                    session.setAttribute("STUDENT_ID", s1.getS_id());
                    session.setAttribute("identity", "student");//身份为学生
                    //学生登录成功，转发到学生端系统主页
                    return "student_index.jsp";
                }
            }
        } else if (sysType.equals("teacher")) {
            //获取工号和密码
            int TeacherId = username;
            String TeacherPwd = password;
            //从数据库Student表中获取工号和密码后进行判断
            if (TeacherId != 0 && TeacherPwd != null) {
                Teacher s = sqlSession.selectOne("mapper.Teacher.findTeacherByTeacherId", TeacherId);
                if (s == null) {
                    //如果工号不在数据库，转发到登录页面并进行提醒
                    model.addAttribute("msg", "用户名错误，请重新登录！");
                    return "login.jsp";
                } else if (!s.getT_pwd().equals(TeacherPwd)) {
                    //如果密码不匹配，转发到登录页面并进行提醒
                    model.addAttribute("msg", "密码错误，请重新登录！");
                    out.println("密码错误，请重新登录");
                    return "login.jsp";
                } else if ((s.getT_id() == TeacherId) && (s.getT_pwd().equals(TeacherPwd))) {
                    session.setAttribute("TEACHER_SESSION", TeacherId);
                    Teacher s1 = sqlSession.selectOne("mapper.Teacher.findTeacherByTeacherId", TeacherId);
                    out.println(s1.getT_name());
                    session.setAttribute("LOGIN_TEACHER", s1);
                    session.setAttribute("TEACHER_NAME", s1.getT_name());
                    session.setAttribute("TEACHER_ID", s1.getT_id());
                    session.setAttribute("identity", "teacher");//身份为教师
                    //教师登录成功，转发到学生端系统主页
                    return "teacher_index.jsp";
                }
            }
        } else if (sysType.equals("manager")) {
            //获取工号和密码
            int ManagerId = username;
            String ManagerPwd = password;
            out.println(ManagerId);
            out.println(ManagerPwd);
            //从数据库Student表中获取工号和密码后进行判断
            if (ManagerId != 0 && ManagerPwd != null) {
                Manager s = sqlSession.selectOne("mapper.Manager.findManagerByManagerId", ManagerId);
                if (s == null) {
                    //如果账号不在数据库，转发到登录页面并进行提醒
                    model.addAttribute("msg", "用户名错误，请重新登录！");
                    return "login.jsp";
                } else if (!s.getM_pwd().equals(ManagerPwd)) {
                    //如果密码不匹配，转发到登录页面并进行提醒
                    model.addAttribute("msg", "密码错误，请重新登录！");
                    out.println("密码错误，请重新登录");
                    return "login.jsp";
                } else if ((s.getM_id() == ManagerId) && (s.getM_pwd().equals(ManagerPwd))) {
                    session.setAttribute("MANAGER_SESSION", ManagerId);
                    Manager m1 = sqlSession.selectOne("mapper.Manager.findManagerByManagerId", ManagerId);
                    out.println(m1.getM_name());
                    session.setAttribute("LOGIN_MANAGER", m1);
                    session.setAttribute("MANAGER_NAME", m1.getM_name());
                    //管理员登录成功，转发到管理员端系统主页
                    return "management_index.jsp";
                }
            }
        }
        return "login.jsp";
    }

    /**
     * 用户退出
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //清除Session
        session.invalidate();
        //退出登录后重定向到登录页面
        return "redirect:tologin";
    }

    /**
     * 学生列表加载
     */
    @RequestMapping(value = "/loadStudentList")
    public String loadStudentList(HttpSession session) throws Exception {
        List<Student> get_students = sqlSession.selectList("mapper.Student.findAllStudent");
        session.setAttribute("get_students", get_students);
        out.println("输出所有学生信息");
        for (Student s : get_students) {
            System.out.println(s.getS_id());
            System.out.println(s.getS_name());
        }
        return "studentList.jsp";
    }

    /**
     * 教师列表加载
     */
    @RequestMapping(value = "/loadTeacherList")
    public String loadTeacherList(HttpSession session) throws Exception {
        List<Teacher> get_teachers = sqlSession.selectList("mapper.Teacher.findAllTeacher");
        session.setAttribute("get_teachers", get_teachers);
        out.println("输出所有教师信息");
        for (Teacher t : get_teachers) {
            System.out.println(t.getT_id());
            System.out.println(t.getT_name());
        }
        return "teacherList.jsp";
    }

    /**
     * 教师端学生列表加载
     */
    @RequestMapping(value = "/loadTeacherStudentList")
    public String loadTeacherStudentList(HttpSession session) throws Exception {
        List<Student> get_teacherStudents = sqlSession.selectList("mapper.Student.teacherStudent");
        session.setAttribute("get_teacherStudents", get_teacherStudents);
        out.println("输出所有学生信息");
        for (Student s : get_teacherStudents) {
            System.out.println(s.getS_id());
            System.out.println(s.getS_name());
        }
        return "teacher_studentList.jsp";
    }

    /**
     * 通过教师姓名查询
     */
    @RequestMapping(value = "/findTeacherByTeacherName")
    public String findTeacherByTeacherName(Teacher teacher, HttpSession session) throws Exception {
        String t_name = teacher.getT_name();//搜素教师名称
        out.println("查询教师，后端java获取到的教师姓名：" + teacher.getT_name());
        List<Teacher> teacherByT_name = sqlSession.selectList("mapper.Teacher.findTeacherByTeacherName", t_name);//找到包含该名字的教师
        if (teacherByT_name == null) {//查找为空
            out.println("数据为空");
        } else {
            session.setAttribute("get_teachers", teacherByT_name);//设置找到的教师为session对象
        }
        for (Teacher t : teacherByT_name) {
            out.println("通过教师姓名查询教师结果如下：");
            System.out.println(t.getT_id());
            System.out.println(t.getT_name());
            out.println(t.getT_pwd());
            System.out.println(t.getT_phone());
        }
        return "teacherList.jsp";
    }

    /**
     * 通过学生姓名查询
     */
    @RequestMapping(value = "/findStudentByStudentName")
    public String findStudentByStudentName(Student student, HttpSession session) throws Exception {
        String s_name = student.getS_name();//搜素学生姓名
        out.println("查询学生，后端java获取到的学生姓名：" + student.getS_name());
        List<Student> studentByS_name = sqlSession.selectList("mapper.Student.findStudentByStudentName", s_name);//找到包含该名字的学生
        if (studentByS_name == null) {//查找为空
            out.println("数据为空");
        } else {
            session.setAttribute("get_students", studentByS_name);//设置找到的学生为session对象
        }
        for (Student s : studentByS_name) {
            out.println("通过学生姓名查询学生结果如下：");
            System.out.println(s.getS_id());
            System.out.println(s.getS_name());
            out.println(s.getS_pwd());
        }
        return "studentList.jsp";
    }

    /**
     * 通过学号查询
     */
    @RequestMapping(value = "/findStudentByStudentId")
    public String findStudentByStudentId(Student student, HttpSession session) throws Exception {
        int s_id = student.getS_id();//搜素学生姓名
        out.println("查询学生，后端java获取到的学生姓名：" + student.getS_name());
        List<Student> studentByS_id = sqlSession.selectList("mapper.Student.findStudentByStudentName", s_id);//找到包含该id的学生
        if (studentByS_id == null) {//查找为空
            out.println("数据为空");
        } else {
            session.setAttribute("get_students", studentByS_id);//设置找到的学生为session对象
        }
        for (Student s : studentByS_id) {
            out.println("通过学生学号查询学生结果如下：");
            System.out.println(s.getS_id());
            System.out.println(s.getS_name());
            out.println(s.getS_pwd());
        }
        return "studentList.jsp";
    }

    /**
     * 教师端通过学生姓名查询
     */
    @RequestMapping(value = "/findTeacherStudentByStudentName")
    public String findTeacherStudentByStudentName(Student student, HttpSession session) throws Exception {
        String s_name = student.getS_name();//搜素学生姓名
        out.println("查询学生，后端java获取到的学生姓名：" + student.getS_name());
        List<Student> teacherStudentByS_name = sqlSession.selectList("mapper.Student.findTeacherStudentByStudentName", s_name);//找到包含该名字的学生
        if (teacherStudentByS_name == null) {//查找为空
            out.println("数据为空");
        } else {
            session.setAttribute("get_teacherStudents", teacherStudentByS_name);//设置找到的学生为session对象
        }
        for (Student s : teacherStudentByS_name) {
            out.println("通过学生姓名查询学生结果如下：");
            System.out.println(s.getS_id());
            System.out.println(s.getS_name());
            out.println(s.getS_pwd());
        }
        return "teacher_studentList.jsp";
    }

    /**
     * 添加学生
     */
    @RequestMapping("/addStudent")
    public String addStudent(Student student, Model model, HttpSession session) {
        Student student1 = new Student();
        int studentId = student.getS_id();
        String studentName = student.getS_name();
        String studentCollege = student.getCollege();
        String studentClass = student.getS_class();
        String studentPhone = student.getS_phone();
        String studentPassword = student.getS_pwd();
        student1.setS_id(studentId);
        student1.setS_name(studentName);
        student1.setCollege(studentCollege);
        student1.setS_class(studentClass);
        student1.setS_phone(studentPhone);
        student1.setS_pwd(studentPassword);
        out.println(studentId + studentName + studentCollege + studentClass + studentPhone + studentPassword);
        //判断用户是否已存在
        if (studentId != 0 && (!studentName.equals("")) && (!studentCollege.equals("")) && (!studentClass.equals("")) && (!studentPhone.equals("")) && (!studentPassword.equals(""))) {
            Student u = sqlSession.selectOne("mapper.Student.findStudentByStudentIds", studentId);
            if (u != null) {
                //如果用户名已存在，转发到添加学生页面并继续提醒
                model.addAttribute("wrongAddMsg", "该学生已存在！");
                out.println("该学生已存在");
                return "student_add.jsp";
            } else {
                //学生还没有注册则注册新账号
                int rows = sqlSession.insert("mapper.Student.addStudent", student1);
                if (rows > 0) {
                    out.print("您成功插入了" + rows + "个学生！\n");
                } else {
                    out.print("执行插入操作失败！\n");
                }
                sqlSession.commit();
                return "loadStudentList";
            }
        }
        return "student_add.jsp";
    }

    /**
     * 删除学生
     */
    @RequestMapping("/deleteStudent")
    @ResponseBody
    public boolean deleteStudent(Student student, HttpSession session) {
        try {
            int s_id = student.getS_id();
            out.println("删除的学生姓名为：" + s_id);
            List<Course> cs = sqlSession.selectList("mapper.Course.findCourseByStudentId", s_id);
            int csnum = cs.size();
            out.println("学生课程个数为" + csnum);
            List<Answer> as = sqlSession.selectList("mapper.Answer.findAnswerByStudentId", s_id);
            int asnum = as.size();
            out.println("学生作答个数为" + asnum);
            List<Score> ss = sqlSession.selectList("mapper.Score.findScoreByStudentId", s_id);
            int ssnum = ss.size();
            out.println("学生成绩个数为" + csnum);
            int rows = sqlSession.delete("mapper.Student.deleteStudent", s_id);
            int row1 = sqlSession.delete("mapper.Course.deleteStudentCourse", s_id);
            int row2 = sqlSession.delete("mapper.Answer.deleteStudentAnswers", s_id);
            int row3 = sqlSession.delete("mapper.Score.deleteStudentScores", s_id);
            sqlSession.commit();
            boolean cspd = (csnum > 0 && row1 > 0) || (csnum == 0);
            boolean aspd = (asnum > 0 && row2 > 0) || (asnum == 0);
            boolean sspd = (ssnum > 0 && row3 > 0) || (ssnum == 0);
            if (rows > 0) {
                if (cspd && aspd && sspd) {
                    out.println("删除成功！");
                    return true;
                } else if (!cspd) {
                    out.println("课程删除失败！");
                    return false;
                } else if (!aspd) {
                    out.println("学生作答删除失败！");
                    return false;
                } else {
                    out.println("学生成绩删除失败！");
                    return false;
                }
            } else {
                out.println("学生删除失败！");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("删除时发生异常！");
        }
        return false;
    }

    /**
     * 添加教师
     */
    @RequestMapping("/addTeacher")
    public String addTeacher(Teacher teacher, Model model, HttpSession session) {
        Teacher teacher1 = new Teacher();
        int teacherId = teacher.getT_id();
        String teacherName = teacher.getT_name();
        String teacherPhone = teacher.getT_phone();
        String teacherPassword = teacher.getT_pwd();
        teacher1.setT_id(teacherId);
        teacher1.setT_name(teacherName);
        teacher1.setT_pwd(teacherPassword);
        teacher1.setT_phone(teacherPhone);
        out.println(teacherId + teacherName);
        //判断用户是否已存在
        if (teacherId != 0 && (!teacherName.equals("")) && (!teacherPhone.equals("")) && (!teacherPassword.equals(""))) {
            Teacher u = sqlSession.selectOne("mapper.Teacher.findTeacherByTeacherId", teacherId);
            if (u != null) {
                //如果用户名已存在，转发到添加教师页面并继续提醒
                model.addAttribute("wrongAddTMsg", "该教师已存在！");
                out.println("该教师已存在");
                return "teacher_add.jsp";
            } else {
                //教师还没有注册则注册新账号
                int rows = sqlSession.insert("mapper.Teacher.addTeacher", teacher1);
                if (rows > 0) {
                    out.print("您成功插入了" + rows + "个教师！\n");
                } else {
                    out.print("执行插入操作失败！\n");
                }
                sqlSession.commit();
                return "loadTeacherList";
            }
        }
        return "teacher_add.jsp";
    }

    /**
     * 删除教师
     */
    @RequestMapping("/deleteTeacher")
    @ResponseBody
    public boolean deleteTeacher(Teacher teacher, HttpSession session) {
        try {
            int t_id = teacher.getT_id();
            out.println("删除的教师姓名为：" + t_id);
            List<Course> ct = sqlSession.selectList("mapper.Course.findAllCourseByTeacherId", t_id);
            int ctnum = ct.size();
            out.println("教师课程个数为" + ctnum);
            List<Paper> pt = sqlSession.selectList("mapper.Paper.findPapersByTeacherId", t_id);
            int ptnum = pt.size();
            out.println("教师试卷个数为" + ptnum);
            int rows = sqlSession.delete("mapper.Teacher.deleteTeacher", t_id);
            int row1 = sqlSession.delete("mapper.Course.deleteTeacherCourse", t_id);
            int row2 = sqlSession.delete("mapper.Paper.deleteTeacherPaper", t_id);
            sqlSession.commit();
            boolean ctpd = (ctnum > 0 && row1 > 0) || (ctnum == 0);
            boolean ptpd = (ptnum > 0 && row2 > 0) || (ptnum == 0);
            if (rows > 0) {
                if (ctpd && ptpd) {
                    out.println("删除成功！");
                    return true;
                } else if (!ctpd) {
                    out.println("课程删除失败！");
                    return false;
                } else {
                    out.println("试卷删除失败！");
                    return false;
                }
            } else {
                out.println("教师删除失败！");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("删除时发生异常！");
        }
        return false;
    }

    /**
     * 修改教师信息
     */
    @RequestMapping("/UpdateTeacher")
    public String UpdateTeacher(Teacher teacher, HttpSession session) {
        Teacher teacher1 = new Teacher();
        teacher1.setT_id(teacher.getT_id());
        teacher1.setT_name(teacher.getT_name());
        teacher1.setT_pwd(teacher.getT_pwd());
        teacher1.setT_phone(teacher.getT_phone());
        out.println(teacher1.getT_id() + teacher1.getT_name());
        int rows = sqlSession.update("mapper.Teacher.updateTeacher", teacher1);
        sqlSession.commit();
        if (rows > 0) {
            out.println("您成功修改了" + rows + "条教师数据！\n");
        } else {
            out.println("执行修改操作失败！\n");
        }

        return "login.jsp";
    }

    /**
     * 修改学生信息
     */
    @RequestMapping("/UpdateStudent")
    public String UpdateStudent(Student student, HttpSession session) {
        Student student1 = new Student();
        student1.setS_id(student.getS_id());
        student1.setS_name(student.getS_name());
        student1.setCollege(student.getCollege());
        student1.setS_class(student.getS_class());
        student1.setS_phone(student.getS_phone());
        student1.setS_pwd(student.getS_pwd());
        out.println(student.getS_id() + student.getS_name());
        int rows = sqlSession.update("mapper.Student.updateStudent", student1);
        sqlSession.commit();
        if (rows > 0) {
            out.println("您成功修改了" + rows + "条学生数据！\n");
        } else {
            out.println("执行修改操作失败！\n");
        }
        return "login.jsp";
    }

    /**
     * 修改管理员信息
     */
    @RequestMapping("/UpdateManager")
    public String UpdateManager(Manager manager, HttpSession session) {
        Manager manager1 = new Manager();
        manager1.setM_id(manager.getM_id());
        manager1.setM_name(manager.getM_name());
        manager1.setM_pwd(manager.getM_pwd());
        manager1.setM_phone(manager.getM_phone());
        out.println(manager1.getM_id() + manager1.getM_name());
        int rows = sqlSession.update("mapper.Manager.updateManager", manager1);
        if (rows > 0) {
            out.println("您成功修改了" + rows + "条管理员数据！\n");
        } else {
            out.println("执行修改操作失败！\n");
        }
        sqlSession.commit();
        return "login.jsp";
    }
}